const path = require('path');
const webpack = require('webpack');
const platform = process.env.PLATFORM;
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const fs = require('fs');
const md5 = require('md5');

const getHash = function (localPath) {
  let file = fs.readFileSync(localPath);
  return md5(file);
};

const resolve = function(_path) {
  return path.resolve(process.cwd(), _path)
};

module.exports = {
  // 构件生产模式时是否生成source map（仅在process.env.NODE_ENV === 'production' 时该选项生效）
  productionSourceMap: false,

  // 开启eslint格式化代码
  lintOnSave: false,
  configureWebpack: config => {


    // 暴露 Megalo Api
    config.plugins.push(new webpack.ProvidePlugin({
      'Megalo': [path.resolve(`./node_modules/@megalo/api/platforms/${platform}`), 'default']
    }));

    config.plugins.push(new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, 'dist-static')]
    }));

    return config;
  },
  chainWebpack: chainConfig => {
    // 这个模式会把static的图片分类出c来，需要同步上传到cdn服务器
    chainConfig.plugin('copy-webpack-plugin').tap(oldArgs => {
      oldArgs[0].push({
        context: resolve('src/static'),
        from: `**/*`,
        to: resolve(`dist-static`),
        transformPath(targetPath, absolutePath) {
          let filename = path.basename(absolutePath).split('.')[0];
          let ext = absolutePath.split('.').reverse()[0];
          let hash = getHash(absolutePath).substr(0,8);
          return '../dist-static/' + filename + '.' + hash + '.' + ext;
        },
      });
      return oldArgs
    });

    chainConfig.module
      .rule('picture')
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 1,
        emitFile: false, // 禁止webpack生成图片到dist目录
        name: (localPath) => localPath,
        publicPath: (localPath) => {
          let filename = path.basename(localPath).split('.')[0];
          let ext = localPath.split('.').reverse()[0];
          let hash = getHash(localPath).substr(0,8);
          return `${process.env.VUE_APP_API_DOMAIN}/mp-static/` + filename + '.' + hash + "." + ext;
        }
      })
  },
  // 原生小程序组件存放目录，默认为src/native
  // 如果你有多个平台的原生组件，你应当在此目录下再新建几个子文件夹，我们约定，子文件夹名和平台的名字一致:
  // 微信小程序组件则命名为 'wechat'，支付宝为'alipay', 百度为 'swan'
  // 如果只有一个平台，则无需再新建子文件夹
  nativeDir: '/src/native',

  css: {
    loaderOptions: {
      css: {
        // https://github.com/webpack-contrib/css-loader#options
      },
      less: {
        // https://github.com/webpack-contrib/less-loader
      },
      sass: {
        // https://github.com/webpack-contrib/sass-loader
      },
      stylus: {
        // https://github.com/shama/stylus-loader
      },
      // https://github.com/megalojs/megalo-px2rpx-loader
      px2rpx: {
        rpxUnit: 1
      }
    }
  }
}
